import { loggerProvider } from '@app/common/constants';
import { HttpExceptionFilter } from '@app/common/filters/httpexception/httpexception.filter';
import { Account } from '@app/common/types/account.type';
import { AccountService } from '@app/services/account/account.service';
import {
  Body,
  Controller,
  Get,
  Inject,
  Logger,
  Post,
  UnauthorizedException,
  UseFilters,
  UseInterceptors,
} from '@nestjs/common';

@Controller('account')
@UseFilters(new HttpExceptionFilter())
@UseInterceptors()
export class AccountController {
  constructor(
    @Inject(loggerProvider)
    private readonly logger: Logger,
    private readonly accountService: AccountService,
  ) {}

  @Get('/init')
  async init() {
    await this.accountService.initData();
    return true;
  }

  @Get('/has')
  async get() {
    return await this.accountService.hasInitData();
  }

  @Post('/login')
  async login(@Body() account: Pick<Account, 'account' | 'password'>) {
    const token = await this.accountService.signIn(account);
    if (!token) {
      this.logger.warn('The Token is invalid');
      throw new UnauthorizedException();
    }
    return token;
  }
}
